{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "# Time Series Forecasting\n",
    "\n",
    "\n",
    "In this example, we use a feature representation pipeline to forecast a continuous time series\n",
    "target with a regressor.\n",
    "\n",
    "The algorithm is trained from the target from the features and targets in the training set.\n",
    "Then predict (future segments) from the features in the test set.\n",
    "\n",
    "We do not sequentially retrain the algorithm as we move through the test set - which is an\n",
    "approach you will sometimes see with time series forecasting (and which may or may not be\n",
    "useful in your application).\n",
    "\n",
    "滑动窗口模型，把时间颗粒化，变成一个段落式的，其中：SegmentXYForecast中的width是控制每个颗粒大小的；譬如有5000样本，width为100，那么时间颗粒理论上为50，当然了此时还有可能就是两个颗粒的时间段是相连的，通过overlap，代表，前一段时间颗粒一部分也是下一个时间颗粒的一部分。\n",
    "forecast应该可以说是一种预测范围圈定的方式，forecast越大，中间gap越多，不可预测的范围越大。\n",
    "\n",
    "疑问:\n",
    "\n",
    "    都是监督式的，往前预测一段未知时间段，那么该如何进行呢？\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Author: David Burns\n",
    "# License: BSD\n",
    "\n",
    "\n",
    "from seglearn.transform import FeatureRep, SegmentXYForecast, last,mean\n",
    "from seglearn.pipe import SegPipe\n",
    "from seglearn.split import temporal_split\n",
    "\n",
    "from sklearn.pipeline import Pipeline\n",
    "from sklearn.linear_model import LinearRegression\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "t = np.arange(5000)/100.\n",
    "y = np.sin(t)*t*2.5 + t*t\n",
    "\n",
    "# with forecasting, X can include the target\n",
    "X = np.stack([t, y], axis = 1)\n",
    "\n",
    "# remember for a single time series, we need to make a list\n",
    "X = [X]\n",
    "y = [y]\n",
    "\n",
    "# 分割训练集与测试集\n",
    "# split the data along the time axis (our only option since we have only 1 time series)\n",
    "X_train, X_test, y_train, y_test = temporal_split(X, y, test_size=0.25) \n",
    "\n",
    "# X_train (1, 3750, 2)\n",
    "# y_train (,3750)\n",
    "# 两个自变量，一个因变量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "# create a feature representation pipeline\n",
    "est = Pipeline([('features', FeatureRep()),\n",
    "                ('lin', LinearRegression())])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "# setting y_func = last, and forecast = 200 makes us predict the value of y\n",
    "# 200 samples ahead of the segment\n",
    "# other reasonable options for y_func are ``mean``, ``all`` (or create your own function)\n",
    "# see the API documentation for further details\n",
    "segmenter = SegmentXYForecast(width = 200, overlap=0.5, y_func=last, forecast=200)\n",
    "    # width，滑动窗口长度，此时时序数据就划分成：5000/width 段\n",
    "    #overlap，窗口之间重叠内容范围，[0,1]\n",
    "    # y_func,有点像分位数回归，从哪个分位点开始，'last'/'mean'，两种选项\n",
    "    # forecast,往前预测的区间范围\n",
    "pipe = SegPipe(est, segmenter)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.9961701854917012"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# fit and score\n",
    "pipe.fit(X_train,y_train)\n",
    "score = pipe.score(X_test, y_test)\n",
    "score"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "# generate some predictions\n",
    "# 返回；y真值；y_p预测值\n",
    "y, y_p = pipe.predict(X, y) # all predictions \n",
    "ytr, ytr_p = pipe.predict(X_train, y_train) # training predictions\n",
    "yte, yte_p = pipe.predict(X_test, y_test) # test predictions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### ------------------------------ 完整内容  ------------------------------ "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "N series in train:  1\n",
      "N series in test:  1\n",
      "N segments in train:  72\n",
      "N segments in test:  22\n",
      "Gap length:  3\n",
      "Predict length:  22\n",
      "Score:  0.9978120706071804\n"
     ]
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAZIAAAEKCAYAAAA4t9PUAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDIuMS4wLCBo\ndHRwOi8vbWF0cGxvdGxpYi5vcmcvpW3flQAAIABJREFUeJzt3Xl8VOX59/HPlc0oICAgshpUCqhg\nCJHlQVupVdHyU2txt2JbpA9VS3+trdZarfprH+1i1daloP6wLdW6g9YqqFBxQUgwKpsaNECQArIp\nsmSZ6/ljTuIkZCWzZGa+79crr5y55yz3yeBc3su5bnN3RERE9ldGoisgIiLJTYFERETaRIFERETa\nRIFERETaRIFERETaRIFERETaRIFERETaRIFERETaRIFERETaJCvRFYiF7t27e15eXqKrISKSVIqL\niz9x9x6tPS4lA0leXh5FRUWJroaISFIxszX7c5y6tkREpE0USEREpE1iFkjMrJ+ZzTezFWa23Mym\nBeW/NLP1ZlYS/JwRcczPzKzUzN4zs9MiyscHZaVmdm2s6iwiIq0XyzGSKuDH7r7UzDoBxWY2L3jv\nD+7+u8idzexo4ALgGKA38KKZfSl4+27gFKAcWGJmc9x9RWsqU1lZSXl5OXv27GnDLQlAbm4uffv2\nJTs7O9FVEZF2IGaBxN03ABuC7c/MbCXQp4lDzgIecfe9wEdmVgqMDN4rdfcPAczskWDfVgWS8vJy\nOnXqRF5eHmbWyruRGu7Oli1bKC8vZ8CAAYmujoi0A3EZI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RfkV4HYgavwOmmtlbhDO47o89\nwfH38cVa5LcA2cA7ZrY8eC3Sasr+K2nJzDq6+85g+1qgl7tPS3C1RJKSxkgkXX3dzH5G+L+BNcBl\nia2OSPJSi0RERNpEYyQiItImCiQiItImCiQiItImCiQiItImCiQiItImCiQiItIm/x8OX0RYCBfA\nJQAAAABJRU5ErkJggg==\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x7f5d9f351320>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Author: David Burns\n",
    "# License: BSD\n",
    "\n",
    "\n",
    "from seglearn.transform import FeatureRep, SegmentXYForecast, last\n",
    "from seglearn.pipe import SegPipe\n",
    "from seglearn.split import temporal_split\n",
    "\n",
    "from sklearn.pipeline import Pipeline\n",
    "from sklearn.linear_model import LinearRegression\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "t = np.arange(5000)/100.\n",
    "y = np.sin(t)*t*2.5 + t*t\n",
    "\n",
    "# with forecasting, X can include the target\n",
    "X = np.stack([t, y], axis = 1)\n",
    "\n",
    "# remember for a single time series, we need to make a list\n",
    "X = [X]\n",
    "y = [y]\n",
    "\n",
    "# split the data along the time axis (our only option since we have only 1 time series)\n",
    "X_train, X_test, y_train, y_test = temporal_split(X, y, test_size=0.25)\n",
    "\n",
    "# create a feature representation pipeline\n",
    "est = Pipeline([('features', FeatureRep()),\n",
    "                ('lin', LinearRegression())])\n",
    "\n",
    "# setting y_func = last, and forecast = 200 makes us predict the value of y\n",
    "# 200 samples ahead of the segment\n",
    "# other reasonable options for y_func are ``mean``, ``all`` (or create your own function)\n",
    "# see the API documentation for further details\n",
    "segmenter = SegmentXYForecast(width = 100, overlap=0.5, y_func=last, forecast=100)\n",
    "pipe = SegPipe(est, segmenter)\n",
    "\n",
    "# fit and score\n",
    "pipe.fit(X_train,y_train)\n",
    "score = pipe.score(X_test, y_test)\n",
    "\n",
    "\n",
    "# generate some predictions\n",
    "y, y_p = pipe.predict(X, y) # all predictions\n",
    "ytr, ytr_p = pipe.predict(X_train, y_train) # training predictions\n",
    "yte, yte_p = pipe.predict(X_test, y_test) # test predictions\n",
    "\n",
    "\n",
    "# note - the first few segments in the test set won't have predictions (gap)\n",
    "# test之中，前几个不会有预测值\n",
    "# we plot the 'gap' for the visualization to hopefully make the situation clear\n",
    "Ns = len(y)\n",
    "ts = np.arange(Ns) # segment number\n",
    "ttr = ts[0:len(ytr)]\n",
    "tte = ts[(Ns - len(yte)):Ns]\n",
    "tga = ts[len(ytr):(Ns - len(yte))]\n",
    "yga = y[len(ytr):(Ns - len(yte))]\n",
    "\n",
    "\n",
    "# plot the results\n",
    "plt.plot(ttr, ytr, '.', label =\"training\")        # 训练集真值\n",
    "#plt.plot(ttr, ytr_p, '.', label =\"training pred\") # 训练集预测\n",
    "plt.plot(tga, yga, '.', label =\"gap\")             # \n",
    "plt.plot(tte, yte, '.', label =\"test\")            # test真值\n",
    "plt.plot(tte, yte_p, label =\"predicted\")          # test预测值\n",
    "\n",
    "#\n",
    "print(\"N series in train: \", len(X_train))\n",
    "print(\"N series in test: \", len(X_test))\n",
    "print(\"N segments in train: \", pipe.N_train)\n",
    "print(\"N segments in test: \", pipe.N_test)\n",
    "print(\"Gap length: \", len(tga))\n",
    "print(\"Predict length: \", len(tte))\n",
    "print(\"Score: \", score)\n",
    "\n",
    "plt.xlabel(\"Segment Number\")\n",
    "plt.ylabel(\"Target\")\n",
    "plt.legend()\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
